package com.donger.business.service;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.donger.auth.component.BootUserDetailsService;
import com.donger.auth.component.UserDetail;
import com.donger.business.entity.UserInfo;
import com.donger.business.modules.upms.entity.SysUser;
import com.donger.business.modules.upms.service.ISysSocialDetailsService;
import com.donger.business.modules.upms.service.ISysUserService;
import com.donger.common.core.constant.CommonConstants;
import com.donger.common.core.constant.SecurityConstants;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * 用户认证service
 *
 * @author xyx
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class UserDetailsServiceImpl implements BootUserDetailsService {

    private final ISysUserService sysUserService;

    private final ISysSocialDetailsService sysSocialDetailsService;

    /**
     * 用户名密码登陆
     * <p>
     *
     * @param phone
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String phone) throws UsernameNotFoundException {
        SysUser queryObj = new SysUser();
        queryObj.setPhone(phone);
        SysUser currentUser = sysUserService.getOne(Wrappers.query(queryObj));
        return getUser(currentUser);
    }

    /**
     * 社交账号登陆
     *
     * @param code
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserBySocial(String code) throws UsernameNotFoundException {
        log.info("手机号为code -> {}", code);
        SysUser user = sysSocialDetailsService.socialUserInfo(code);
        return getUser(user);
    }

    private UserDetails getUser(SysUser currentUser) {
        if (currentUser == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        UserInfo info = sysUserService.findUserInfo(currentUser);
        Set<String> authSet = new HashSet<>();
        if(ArrayUtil.isNotEmpty(info.getRoles())){
            // 获取角色
            Arrays.stream(info.getRoles()).forEach(roleId -> authSet.add(SecurityConstants.ROLE + roleId));
            // 获取资源
            authSet.addAll(Arrays.asList(info.getPermissions()));
        }

        Collection<? extends GrantedAuthority> authorities
                = AuthorityUtils.createAuthorityList(authSet.toArray(new String[0]));

        SysUser user = info.getSysUser();
        boolean enabled = StrUtil.equals(user.getStatus(), CommonConstants.STATUS_NORMAL);

        return new UserDetail(currentUser.getUserId(), currentUser.getDeptId(), currentUser.getUsername(), SecurityConstants.BCRYPT + currentUser.getPassword()
                ,enabled, true, true,enabled,authorities);
    }

}
